package com.ce.server.service.impl;

import cn.hutool.core.date.LocalDateTimeUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ce.server.common.RespBean;
import com.ce.server.common.RespPageBean;
import com.ce.server.common.Today;
import com.ce.server.mapper.ClockInMapper;
import com.ce.server.mapper.StudentMapper;
import com.ce.server.pojo.ClockIn;
import com.ce.server.pojo.Student;
import com.ce.server.service.IClockInService;
import com.ce.server.util.AdminUtil;
import com.ce.server.util.TimeUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.message.ReusableMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 郑爽
 * @since 2021-11-17
 */
@Service
@Slf4j
@Order(value = 2)
public class ClockInServiceImpl extends ServiceImpl<ClockInMapper, ClockIn> implements IClockInService, CommandLineRunner {

    @Autowired
    ClockInMapper clockInMapper;
    @Autowired
    StudentMapper studentMapper;

    @Value("${type.student}")
    private String type;

    /**
     * 每次项目启动的时候都会去检测是否已经创建待打卡记录
     * @param args
     * @throws Exception
     */
    @Override
    @Transactional
    public void run(String... args) throws Exception {
        LocalDateTime maxCreateTime = clockInMapper.getMaxCreateTime();
        if(!TimeUtil.isToday(maxCreateTime)){
            log.info("今天还没有创建!");
            everydayCreateClockIn();
            return;
        }
        log.info("今天已经创建所有学生的待打卡记录");
        return;
    }


    /**
     * 每天00点 异步创建待打卡记录
     */
    @Override
    @Async
    @Scheduled(cron = "0 0 0 1/1 * ?")
    @Transactional
    public void everydayCreateClockIn() {
        log.info("今天的待打卡记录开始创建------");
        LocalDateTime beginTime = LocalDateTimeUtil.beginOfDay(LocalDateTime.now());
        List<String> snos = studentMapper.getAllSno();
        clockInMapper.insertByBatchSno(snos,beginTime);
    }

    /**
     * 根据学号获取该学生最新时间的一个记录
     *
     * @param sno
     * @return
     */
    @Override
    public ClockIn getClockInByToday(String sno) {
        Today toDay = TimeUtil.getBeginAndEndByToDay();
        ClockIn clockIn =
                clockInMapper.selectOne(new LambdaQueryWrapper<ClockIn>().eq(ClockIn::getSno, sno).between(ClockIn::getCreateTime
                        , toDay.getBegin(), toDay.getEnd()));
        return clockIn;
    }

    /**
     * 提交打卡信息(update)
     *
     * @param clock
     * @return
     */
    @Override
    public boolean commitClockInMessage(ClockIn clock) {
        String sno = ((Student) AdminUtil.getCurrentAdmin()).getSno();
        clock.setClockInTime(LocalDateTime.now()).setSno(sno);
        //获取学生最近的一次打卡记录
        ClockIn clockInByLatestTime = getClockInByToday(clock.getSno());

        //如果存在打卡记录且最近的一次打卡是今天的话, 做更新操作
        if (clockInByLatestTime != null) {
            clock.setId(clockInByLatestTime.getId());
            return clockInMapper.updateById(clock) == 1;
        }
        return false;
    }

    /**
     * 分页获取全部打卡信息
     *
     * @param currentPage
     * @param size
     * @param clockIn
     * @return
     */
    @Override
    public RespPageBean getClockInsByPage(Integer currentPage, Integer size, ClockIn clockIn, LocalDate[] createTimeScope) {
        Page<ClockIn> page = new Page<>(currentPage, size);
        IPage<ClockIn> clockInByPage = clockInMapper.getClockInByPage(page, clockIn,createTimeScope);
        if (clockInByPage != null)
            return new RespPageBean(clockInByPage.getTotal(), clockInByPage.getRecords());
        return null;
    }

    /**
     * @param isClockIn true 表示 已打卡 ,  false 表示未打卡
     * @return
     */
    @Override
    public RespPageBean getTodayClockInsByPage(Integer currentPage, Integer size, boolean isClockIn) {
        Page<ClockIn> page = new Page<>(currentPage, size);
        Today toDay = TimeUtil.getBeginAndEndByToDay();
        IPage<ClockIn> clockInByPage = clockInMapper.getClockInByPageAndClockIn(page, isClockIn,
                toDay.getBegin(), toDay.getEnd());
        if (clockInByPage != null)
            return new RespPageBean(clockInByPage.getTotal(), clockInByPage.getRecords());
        return null;
    }

  @Override
  public RespBean delRecords(Integer[] ids) {
      int recordNum = clockInMapper.deleteBatchIds(Arrays.stream(ids).collect(Collectors.toList()));
      if (ids.length==recordNum)
          return RespBean.success("批量删除成功！");
      return RespBean.error("批量删除失败！");

  }


}
